﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace SheepCommon.API.SheepFarmHomepage.BreedingHenStock
{
    public class BreedingHenStockQueryHandler : IRequestHandler<BreedingHenStockQueryCommand, Result>
    {
        private readonly IBaseRepository<SheepArchives> _sheepArchivesRepository;

        public BreedingHenStockQueryHandler(IBaseRepository<SheepArchives> sheepArchivesRepository)
        {
            _sheepArchivesRepository = sheepArchivesRepository;
        }
        /// <summary>
        /// 种母存栏结果
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(BreedingHenStockQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            var name = "";
            try
            {
                var breedingHenStockQuery = await (from a in await _sheepArchivesRepository.GetAll()
                                                   where a.RecordType == 0
                                                   select new BreedingHenStockQueryDto()
                                                   {
                                                       name = a.ReproductiveState == 0 ? "待配种" : a.ReproductiveState == 1 ? "待首次妊检" : a.ReproductiveState == 2 ? "待二次妊检" : a.ReproductiveState == 3 ? "待上产床" : a.ReproductiveState == 4 ? "待分娩" : a.ReproductiveState == 5 ? "种母待断奶" : "妊检换料"
                                                   }).Distinct().ToListAsync();

                breedingHenStockQuery = await (from a in await _sheepArchivesRepository.GetAll()
                                               where a.RecordType == 0
                                               group a by a.ReproductiveState into a
                                               select new BreedingHenStockQueryDto()
                                               {
                                                   name = a.Key == 0 ? "待配种" : a.Key == 1 ? "待首次妊检" : a.Key == 2 ? "待二次妊检" : a.Key == 3 ? "待上产床" : a.Key == 4 ? "待分娩" : a.Key == 5 ? "种母待断奶" : "妊检换料",
                                                   value = a.Count(),
                                               }).Distinct().ToListAsync();
                result.Data = breedingHenStockQuery;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
